package cn.wgx.test;


import com.google.common.collect.Maps;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Hello activiti test
 */

public class DemoMain {

        private static final Logger logger = LoggerFactory.getLogger(DemoMain.class);

//    private static String resource = "process/second_approve.bpmn";
//    private static String resource = "process/second_approve.bpmn20.xml";
    private static String resource = "process/second.bpmn20.xml";

    public static void main(String[] args) throws ParseException {
        logger.info("--------------启动程序--------------");

        //创建流程引擎
        ProcessEngine processEngine = getProcessEngine();

        //部署流程文件
        ProcessDefinition processDefinition = getProcessDefinition(processEngine);

        //启动流程
        ProcessInstance processInstance = getProcessInstance(processEngine, processDefinition);


        //处理流程
        processTask(processEngine, processInstance);

        logger.info("--------------结束程序--------------");
    }

    private static void processTask(ProcessEngine processEngine, ProcessInstance processInstance) throws ParseException {
        while(processInstance != null && !processInstance.isEnded()){
            TaskService taskService = getTaskService(processEngine);
            List<Task> list = taskService.createTaskQuery().list();
            Scanner scanner = new Scanner(System.in);
            for(Task task: list){
                logger.info("正在处理任务 [{}]", task.getName());
                FormService formService = processEngine.getFormService();
                TaskFormData taskFormData = formService.getTaskFormData(task.getId());
                List<FormProperty> formProperties = taskFormData.getFormProperties();
                Map<String, Object> map = Maps.newHashMap();
                for(FormProperty formProperty: formProperties){
                    String line = "";
                    if(StringFormType.class.isInstance(formProperty.getType())){
                        logger.info("请输入[{}]:", formProperty.getName());
                        line = scanner.nextLine();
                        map.put(formProperty.getId(), line);
                    }else if(DateFormType.class.isInstance(formProperty.getType())){
                        logger.info("请输入[{}],格式: yyyy-MM-dd", formProperty.getName());
                        line = scanner.nextLine();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        map.put(formProperty.getId(), sdf.parse(line));
                    }
                    logger.info("您输入的是{}", line);
                }
                taskService.complete(task.getId(), map);
                processInstance = processEngine.getRuntimeService()
                         .createProcessInstanceQuery()
                         .processInstanceId(processInstance.getId())
                         .singleResult();
            }

        }
    }


    private static TaskService getTaskService(ProcessEngine processEngine) {
        TaskService taskService = processEngine.getTaskService();
        List<Task> list = taskService.createTaskQuery().list();
        for(Task task: list){
            logger.info("待处理任务 [{}]", task.getName());
        }
        logger.info("待处理任务数量为 [{}]", list.size());
        return taskService;
    }

    private static ProcessInstance getProcessInstance(ProcessEngine processEngine, ProcessDefinition processDefinition) {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        logger.info("启动流程[{}]", processInstance.getProcessDefinitionKey());
        return processInstance;
    }

    private static ProcessDefinition getProcessDefinition(ProcessEngine processEngine) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        deploymentBuilder.addClasspathResource(resource);
        Deployment deployment = deploymentBuilder.deploy();
        String deploymentId = deployment.getId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
        logger.info("流程定义文件{}, 流程ID是{}", processDefinition.getName(), processDefinition.getId());
        return processDefinition;
    }

    private static ProcessEngine getProcessEngine() {
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        ProcessEngine processEngine = cfg.buildProcessEngine();
        String name = processEngine.getName();
        String version = ProcessEngine.VERSION;
        logger.info("流程引擎名称为[{}],版本为[{}]",name , version);
        return processEngine;
    }

}
